package com.yyfax.ph.personal.authority.forgot;

import com.yyfax.infrastructure.eventbus.EventAgent;
import com.yyfax.infrastructure.mvp.IView;
import com.yyfax.infrastructure.mvp.PresenterFactory;
import com.yyfax.infrastructure.secure.RSA;
import com.yyfax.infrastructure.statistics.StatService;
import com.yyfax.ph.StatIDSet;
import com.yyfax.ph.base.YJPH;
import com.yyfax.ph.common.GlobalVariableConfig;
import com.yyfax.ph.personal.authority.RSAPresenter;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

public class ForgotPwdPresenter extends RSAPresenter<ForgotPwdModel, ForgotPwdPresenter.View> {
	private static final String TAG = ForgotPwdPresenter.class.getSimpleName();
	private View mView;


	public static class Generator implements PresenterFactory<ForgotPwdPresenter> {
		@Override
		public ForgotPwdPresenter create() {
			return new ForgotPwdPresenter();
		}
	}

	@Override
	public void attach(View view) {
		mView = view;
		mModel = new ForgotPwdModel();
		EventAgent.register(this);
	}

	@Override
	public void detach() {
		mView = null;
		mModel = null;
		EventAgent.unregister(this);
	}

	public interface View extends IView {
		ForgotPwdModel.ForgotPwdParams getForgotPwdParams();

		void retrievePwdSuccess();

		void retrievePwdFailure(String tips);
	}

	/**
	 * 加密用户名，密码参数
	 *
	 * @return 加密后的请求参数
	 */
	@Override
	public Object getRSAParams(Object params, int functionalCode) {
		ForgotPwdModel.ForgotPwdParams login = (ForgotPwdModel.ForgotPwdParams) params;
		String keyRSA = GlobalVariableConfig.getKeyRSA();
		login.loginName = RSA.encryptByPublicKey(login.loginName, keyRSA);
		login.password = RSA.encryptByPublicKey(login.password, keyRSA);
		return login;
	}

	/**
	 * 找回密码
	 */
	public void retrievePwd() {
		execute(mView.getForgotPwdParams());
	}

	@Subscribe(threadMode = ThreadMode.MAIN)
	public void retrievePwdResult(ForgotPwdModel.RetrievePwdResult retrievePwdResult) {
		StatService.onEventFirstKeyAttribute(YJPH.getInstance(), StatIDSet.EVENT_ID_E042, retrievePwdResult.getStatus());
		if (isResponseSuccess(retrievePwdResult)) {
			mView.retrievePwdSuccess();
		} else {
			mView.retrievePwdFailure(retrievePwdResult.getMsg());
		}
	}
}
